﻿using System.Windows;
using hygge_imaotai.Domain;
using hygge_imaotai.Entity;
using hygge_imaotai.Repository;

namespace hygge_imaotai.UserInterface.UserControls {
    /// <summary>
    /// LogUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class LogUserControl {
        public LogUserControl() {
            InitializeComponent();
            DataContext = new LogListViewModel();
            QueryData();
        }

        private void QueryData() {
            var logListViewModel = (LogListViewModel)DataContext;
            LogListViewModel.LogList.Clear();

            DB.Sqlite.Select<LogEntity>()
                .WhereIf(!string.IsNullOrEmpty(logListViewModel.Mobile),
                    i => i.MobilePhone.Contains(logListViewModel.Mobile))
                .WhereIf(!string.IsNullOrEmpty(logListViewModel.SearchContent),
                    i => i.Content.Contains(logListViewModel.SearchContent))
                .WhereIf(!string.IsNullOrEmpty(logListViewModel.Status),
                    i => i.Status.Contains(logListViewModel.Status))
                .OrderByDescending(a=> a.Id)
                .Count(out var count)
                .Page(1, 10)
                .ToList()
                .ForEach(LogListViewModel.LogList.Add);

            // 分页数据
            var pageCount = count / 10 + 1;
            logListViewModel.Total = count;
            logListViewModel.PageCount = pageCount;
        }

        private void RefreshLogButton_OnClick(object sender, RoutedEventArgs e) {
            QueryData();
        }

        private void QueryButton_OnClick(object sender, RoutedEventArgs e) {
            QueryData();
        }

        private void ResetButton_OnClick(object sender, RoutedEventArgs e) {
            var logListViewModel = (LogListViewModel)DataContext;
            logListViewModel.Mobile = "";
            logListViewModel.Status = "";
            logListViewModel.SearchContent = "";
        }

        private void BtnClear_OnClick(object sender, RoutedEventArgs e) {
            var dr = MessageBox.Show("确定要删除所有日志吗？", "确认", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk);
            if (dr != MessageBoxResult.OK) return;

            var rows = DB.Sqlite.Delete<LogEntity>().Where("1=1").ExecuteAffrows();
            MessageBox.Show($"操作成功，共删除[{rows}]条日志。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            QueryData();
        }
    }
}
